// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.FeeManage;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.FeeManageMapper;
import com.fowo.api.mapper.FeeManagerSonMapper;
import com.fowo.api.model.fee.manage.FeeManageAddFeesAction;
import com.fowo.api.model.fee.manage.FeeManageAddModleAction;
import com.fowo.api.model.fee.manage.FeeManageCancellationAction;
import com.fowo.api.model.fee.manage.FeeManageExcelPo;
import com.fowo.api.model.fee.manage.FeeManageFeeModelManagerAction;
import com.fowo.api.model.fee.manage.FeeManageFeeTypeManageAction;
import com.fowo.api.model.fee.manage.FeeManageImportPo;
import com.fowo.api.model.fee.manage.FeeManageItemVo;
import com.fowo.api.model.fee.manage.FeeManageSearchParamPo;
import com.fowo.api.model.fee.manage.FeeManageVo;
import com.fowo.api.model.fee.manager.son.FeeManagerSonItemVo;
import com.fowo.api.model.fee.manager.son.FeeManagerSonItemVoPages;
import com.fowo.api.model.fee.manager.son.FeeManagerSonSearchParamPo;
import com.fowo.api.service.FeeManageService;
import com.fowo.api.service.FeeManagerSonService;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartFile;

/**
 * 费用管理 服务实现基类
 * @author 蜂窝蜜造平台 配置人：李玉娇，鹿丙涛
 */
@Slf4j
@DataObjectType(FeeManage.class)
@DS("ds24")
public class FeeManageBaseServiceImpl
  extends ServiceImpl<FeeManageMapper, FeeManage>
  implements FeeManageService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("createUserName", "su.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected FeeManageService self;

  @Resource
  protected FeeManagerSonService feeManagerSonService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected FeeManageCancellationAction feeManageCancellationAction;

  @Autowired(required = false)
  protected FeeManageAddModleAction feeManageAddModleAction;

  @Autowired(required = false)
  protected FeeManageAddFeesAction feeManageAddFeesAction;

  @Resource
  private ExecuteScriptEngine executeScriptEngine;

  @Autowired(required = false)
  protected FeeManageFeeTypeManageAction feeManageFeeTypeManageAction;

  @Autowired(required = false)
  protected FeeManageFeeModelManagerAction feeManageFeeModelManagerAction;

  @Resource
  protected Validator validator;

  /**
   * 创建费用管理
   * @param model 费用管理
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(FeeManageVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FeeManage entity = new FeeManage();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getApportionStatus() == null) {
      entity.setApportionStatus("0");
    }

    if (model.getDimensions() == null) {
      entity.setDimensions("1");
    }

    if (model.getCurrencyCode() == null) {
      entity.setCurrencyCode("CNY");
    }

    if (model.getStatus() == null) {
      entity.setStatus("10");
    }

    if (model.getType() == null) {
      entity.setType("1");
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getFeeCode())) {
      entity.setFeeCode(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "FeeManage.feeCode")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return entity.getId();
    }
    throw new Exception("费用管理保存失败");
  }

  /**
   * 更新所有子表
   * @param model 费用管理
   */
  protected void updateAllChilds(FeeManageVo model) throws Exception {
    if (model.getItemList() != null) {
      feeManagerSonService.saveAllByFeeManagerFormId(
        model.getId(),
        model.getItemList()
      );
    }
  }

  /**
   * 更新费用管理
   * @param model 费用管理
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(FeeManageVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FeeManage entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("费用管理不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "lastUpdateTime",
      "lastUpdateUser",
      "createUser",
      "createTime"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return true;
    }
    return false;
  }/**
   * 更新费用管理（带空值）
   * @param model 费用管理
   * @return 更新是否成功
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(FeeManageVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FeeManage entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("费用管理不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(FeeManage::getLastUpdateTime, model.getLastUpdateTime())
      .set(FeeManage::getLastUpdateUser, model.getLastUpdateUser())
      .set(FeeManage::getFeeCode, model.getFeeCode())
      .set(FeeManage::getDimensions, model.getDimensions())
      .set(FeeManage::getApportionRule, model.getApportionRule())
      .set(FeeManage::getOtherFeeType, model.getOtherFeeType())
      .set(FeeManage::getApportionData, model.getApportionData())
      .set(FeeManage::getExchangeRate, model.getExchangeRate())
      .set(FeeManage::getMoney, model.getMoney())
      .set(FeeManage::getCurrencyCode, model.getCurrencyCode())
      .set(FeeManage::getRevenueAccountType, model.getRevenueAccountType())
      .set(FeeManage::getRemarks, model.getRemarks())
      .set(FeeManage::getStatus, model.getStatus())
      .eq(FeeManage::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(model.getId());
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(FeeManageSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 费用管理子表(itemList) 对应的对象
    FeeManagerSonSearchParamPo itemListSearchParam =
      new FeeManagerSonSearchParamPo();
    itemListSearchParam.setDisableDataPremissions(true);
    itemListSearchParam.setFeeManagerFormIdInList(ids);
    FeeManagerSonMapper localFeeManagerSonMapper = ContextHolder
      .getApplicationContext()
      .getBean(FeeManagerSonMapper.class);
    itemListSearchParam.applySqlSegments();
    List<Long> itemListIdList = localFeeManagerSonMapper.searchIds(
      itemListSearchParam
    );
    if (!itemListIdList.isEmpty()) {
      FeeManagerSonService localFeeManagerSonService = ContextHolder
        .getApplicationContext()
        .getBean(FeeManagerSonService.class);
      localFeeManagerSonService.batchDelete(itemListIdList);
    }
  }

  /**
   * 删除费用管理
   * @param id 费用管理的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除费用管理
   * @param ids 费用管理的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<FeeManageImportPo> excelToImportRow(
    FeeManageImportPo row,
    Integer rowNumber,
    FeeManageVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<FeeManageImportPo> ir = new ImportRow<FeeManageImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<FeeManageImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new FeeManageVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, FeeManageImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getApportionStatus())) {
      List<SysDictAllItem> apportionStatusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "apportionStatus",
          n -> sysDictService.getDictItems("SCM00098")
        );
      FeeManageVo finalVo = vo;
      apportionStatusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getApportionStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setApportionStatus(i.getItemValue()),
          () ->
            ir.addError(
              "apportionStatus",
              String.format(
                "必须为 %s 中之一",
                apportionStatusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getDimensions())) {
      List<SysDictAllItem> dimensionsItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "dimensions",
          n -> sysDictService.getDictItems("SCM00096")
        );
      FeeManageVo finalVo = vo;
      dimensionsItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getDimensions()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setDimensions(i.getItemValue()),
          () ->
            ir.addError(
              "dimensions",
              String.format(
                "必须为 %s 中之一",
                dimensionsItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getApportionRule())) {
      List<SysDictAllItem> apportionRuleItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "apportionRule",
          n -> sysDictService.getDictItems("SCM00097")
        );
      FeeManageVo finalVo = vo;
      apportionRuleItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getApportionRule()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setApportionRule(i.getItemValue()),
          () ->
            ir.addError(
              "apportionRule",
              String.format(
                "必须为 %s 中之一",
                apportionRuleItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getOtherFeeType())) {
      List<SysDictAllItem> otherFeeTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "otherFeeType",
          n -> sysDictService.getDictItems("SCM00229")
        );
      FeeManageVo finalVo = vo;
      otherFeeTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getOtherFeeType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setOtherFeeType(i.getItemValue()),
          () ->
            ir.addError(
              "otherFeeType",
              String.format(
                "必须为 %s 中之一",
                otherFeeTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setApportionData(SheetUtils.tryToDate(row.getApportionData()));
    SheetUtils.datePreviewFormat(row.getApportionData(), row::setApportionData);
    vo.setExchangeRate(SheetUtils.tryToDecimal(row.getExchangeRate()));
    if (StringUtils.hasText(row.getCurrencyCode())) {
      List<SysDictAllItem> currencyCodeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "currencyCode",
          n -> sysDictService.getDictItems("SCM00015")
        );
      FeeManageVo finalVo = vo;
      currencyCodeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getCurrencyCode()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setCurrencyCode(i.getItemValue()),
          () ->
            ir.addError(
              "currencyCode",
              String.format(
                "必须为 %s 中之一",
                currencyCodeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getRevenueAccountType())) {
      List<SysDictAllItem> revenueAccountTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "revenueAccountType",
          n -> sysDictService.getDictItems("SCM00231")
        );
      FeeManageVo finalVo = vo;
      revenueAccountTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getRevenueAccountType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setRevenueAccountType(i.getItemValue()),
          () ->
            ir.addError(
              "revenueAccountType",
              String.format(
                "必须为 %s 中之一",
                revenueAccountTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getStatus())) {
      List<SysDictAllItem> statusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "status",
          n -> sysDictService.getDictItems("SCM00099")
        );
      FeeManageVo finalVo = vo;
      statusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setStatus(i.getItemValue()),
          () ->
            ir.addError(
              "status",
              String.format(
                "必须为 %s 中之一",
                statusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getType())) {
      List<SysDictAllItem> typeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "type",
          n -> sysDictService.getDictItems("SCM00230")
        );
      FeeManageVo finalVo = vo;
      typeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setType(i.getItemValue()),
          () ->
            ir.addError(
              "type",
              String.format(
                "必须为 %s 中之一",
                typeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<FeeManageImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<FeeManageImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            FeeManageImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(FeeManageImportPo row, AnalysisContext cxt) {
              FeeManageVo vo = new FeeManageVo();
              ImportRow<FeeManageImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<FeeManageImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<FeeManageImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      FeeManageVo vo = new FeeManageVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"费用单号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "feeCode".equals(m.getField())
          )
      ) {
        vo.setFeeCode(
          sysSerialService.getNewSerial(
            new NewSerialRequest(null, "FeeManage.feeCode")
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @Override
  public void export(
    Long templateId,
    FeeManageSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "apportionStatus",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00098")
      );
      exportOptions.addFieldMappingOption(
        "dimensions",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00096")
      );
      exportOptions.addFieldMappingOption(
        "apportionRule",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00097")
      );
      exportOptions.addFieldMappingOption(
        "otherFeeType",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00229")
      );
      exportOptions.addFieldMappingOption(
        "apportionData",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "revenueAccountType",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00231")
      );
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00099")
      );
      exportOptions.addStringFields(
        "feeCode",
        "apportionStatus",
        "dimensions",
        "apportionRule",
        "otherFeeType",
        "money",
        "revenueAccountType",
        "remarks",
        "status"
      );

      String fileName = String.format(
        "费用管理(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> apportionStatusItems = sysDictService.getDictItems(
      "SCM00098"
    );
    List<SysDictAllItem> dimensionsItems = sysDictService.getDictItems(
      "SCM00096"
    );
    List<SysDictAllItem> apportionRuleItems = sysDictService.getDictItems(
      "SCM00097"
    );
    List<SysDictAllItem> otherFeeTypeItems = sysDictService.getDictItems(
      "SCM00229"
    );
    List<SysDictAllItem> revenueAccountTypeItems = sysDictService.getDictItems(
      "SCM00231"
    );
    List<SysDictAllItem> statusItems = sysDictService.getDictItems("SCM00099");
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<FeeManageExcelPo> items = new ArrayList<FeeManageExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<FeeManageItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<FeeManageItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (FeeManageItemVo item : list) {
        FeeManageExcelPo excel = new FeeManageExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getApportionStatus() != null) {
          apportionStatusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getApportionStatus()))
            .findFirst()
            .ifPresent(i -> excel.setApportionStatus(i.getItemText()));
        }
        if (item.getDimensions() != null) {
          dimensionsItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getDimensions()))
            .findFirst()
            .ifPresent(i -> excel.setDimensions(i.getItemText()));
        }
        if (item.getApportionRule() != null) {
          apportionRuleItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getApportionRule()))
            .findFirst()
            .ifPresent(i -> excel.setApportionRule(i.getItemText()));
        }
        if (item.getOtherFeeType() != null) {
          otherFeeTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getOtherFeeType()))
            .findFirst()
            .ifPresent(i -> excel.setOtherFeeType(i.getItemText()));
        }
        if (item.getRevenueAccountType() != null) {
          revenueAccountTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getRevenueAccountType()))
            .findFirst()
            .ifPresent(i -> excel.setRevenueAccountType(i.getItemText()));
        }
        if (item.getStatus() != null) {
          statusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getStatus()))
            .findFirst()
            .ifPresent(i -> excel.setStatus(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "费用管理(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(FeeManageExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过费用单号查询费用管理主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByFeeCode(String feeCode) {
    return this.baseMapper.getIdByFeeCode(feeCode);
  }

  /**
   * 通过费用单号查询费用管理多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByFeeCode(List<String> list) {
    return this.baseMapper.getIdsByFeeCode(list);
  }

  /**
   * 通过费用管理主键查询费用单号
   */
  @Override
  public String getFeeCodeById(Long id) {
    return this.baseMapper.getFeeCodeById(id);
  }

  /**
   * 通过费用管理主键查询费用单号列表
   */
  @Override
  public List<String> getFeeCodeByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getFeeCodeByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("feeCode"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 费用管理的主键
   */
  @Override
  public FeeManageVo getVoById(Long id) throws Exception {
    FeeManageVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    FeeManagerSonSearchParamPo itemListSearchParamPo =
      new FeeManagerSonSearchParamPo();
    itemListSearchParamPo.setFeeManagerFormId(id);
    itemListSearchParamPo.getExtendData().put("queryMode", "sub");
    itemListSearchParamPo.getExtendData().put("queryParent", "FeeManage");
    itemListSearchParamPo.applySqlSegments();
    vo.setItemList(feeManagerSonService.search(itemListSearchParamPo));

    return vo;
  }

  /**
   * 分页查询费用管理
   * @param search 查询条件
   * @return 费用管理分页查询结果
   */
  @Override
  public Page<FeeManageItemVo> pageSearch(FeeManageSearchParamPo search) {
    Page<FeeManageItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(FeeManageItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(Page<FeeManageItemVo> pageResult) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<FeeManageItemVo> pageResult,
    String sort
  ) {
    if (
      pageResult == null ||
      pageResult.getRecords() == null ||
      pageResult.getRecords().isEmpty()
    ) {
      return pageResult;
    }
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    FeeManagerSonSearchParamPo itemListSearchParamPo =
      new FeeManagerSonSearchParamPo();
    itemListSearchParamPo.setSort(sort);
    itemListSearchParamPo.setPageSize(5);
    itemListSearchParamPo.setFeeManagerFormIdInList(
      pageResult
        .getRecords()
        .stream()
        .map(FeeManageItemVo::getId)
        .collect(Collectors.toList())
    );

    Map<String, Page<FeeManagerSonItemVoPages>> itemListMaps =
      feeManagerSonService.pagesByFeeManagerFormId(itemListSearchParamPo);

    for (FeeManageItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put("itemList", itemListMaps.get(itemVo.getId().toString()));
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 费用管理分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(FeeManageSearchParamPo search) {
    return appendWithChild(pageSearch(search), search.toChildSort("itemList"));
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    FeeManageSearchParamPo search
  ) {
    FeeManageSearchParamPo parentSearchParam = new FeeManageSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<FeeManageItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      FeeManageItemVo itemVo = parentList.get(0);

      FeeManagerSonSearchParamPo itemListSearchParamPo =
        new FeeManagerSonSearchParamPo();
      itemListSearchParamPo.setPageSize(search.getPageSize());
      itemListSearchParamPo.setCurrent(search.getCurrent());
      itemListSearchParamPo.setFeeManagerFormId(itemVo.getId());
      return feeManagerSonService.pageSearch(itemListSearchParamPo);
    } else {
      return null;
    }
  }

  /**
   * 费用管理快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'FeeManageOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<FeeManageItemVo>> searchOptions(
    FeeManageSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询费用管理
   * @param search 查询条件
   * @return 费用管理列表查询结果
   */
  @Override
  public List<FeeManageItemVo> search(FeeManageSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询费用管理最后更新时间
   * @param search 查询条件
   * @return 费用管理最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(FeeManageSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 作废
   */
  @Override
  public void cancellation(Long id) throws Exception {
    if (feeManageCancellationAction == null) {
      throw new Exception("此操作当前不可用");
    }
    feeManageCancellationAction.run(id);
  }

  /**
   * 加入模板
   */
  @Override
  public void addModle(Long id) throws Exception {
    if (feeManageAddModleAction == null) {
      throw new Exception("此操作当前不可用");
    }
    feeManageAddModleAction.run(id);
  }

  /**
   * 添加费用
   */
  @Override
  public void addFees() throws Exception {
    if (feeManageAddFeesAction == null) {
      throw new Exception("此操作当前不可用");
    }
    feeManageAddFeesAction.run();
  }

  /**
   * 导入费用
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importFees(MultipartFile file) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/FeeManage_importFees.js",
      null,
      new ExecuteScriptEngine.OtherArgs().applyUploadData(file),
      this
    );
  }

  /**
   * 费用类型管理
   */
  @Override
  public void feeTypeManage() throws Exception {
    if (feeManageFeeTypeManageAction == null) {
      throw new Exception("此操作当前不可用");
    }
    feeManageFeeTypeManageAction.run();
  }

  /**
   * 费用模板管理
   */
  @Override
  public void feeModelManager() throws Exception {
    if (feeManageFeeModelManagerAction == null) {
      throw new Exception("此操作当前不可用");
    }
    feeManageFeeModelManagerAction.run();
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    FeeManageSearchParamPo search = new FeeManageSearchParamPo();
    return MapUtil
      .builder()
      .put("AllFee", this.baseMapper.allFeeCount(search))
      .put("WaitSubmit", this.baseMapper.waitSubmitCount(search))
      .put("handled", this.baseMapper.handledCount(search))
      .put("Voided", this.baseMapper.voidedCount(search))
      .build();
  }

  /**
   * 全部
   */
  @Override
  public List<FeeManageItemVo> allFee(FeeManageSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.allFee(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<FeeManageItemVo> allFeePage(FeeManageSearchParamPo search) {
    Page<FeeManageItemVo> allFeePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return allFeePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return allFeePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    allFeePage =
      this.baseMapper.allFeePage(
          search.toPage(this.baseMapper.allFeeCount(search)),
          search
        );
    List<Long> recordIds = allFeePage
      .getRecords()
      .stream()
      .map(FeeManageItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return allFeePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return allFeePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    allFeePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return allFeePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 费用管理分页查询结果
   */
  @Override
  public Page<?> allFeePageWithChildSearch(FeeManageSearchParamPo search) {
    return appendWithChild(allFeePage(search), search.toChildSort("itemList"));
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date allFeeLastUpdateTime(FeeManageSearchParamPo search) {
    return this.baseMapper.allFeeLastUpdateTime(search);
  }

  /**
   * 待提交
   */
  @Override
  public List<FeeManageItemVo> waitSubmit(FeeManageSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.waitSubmit(search);
  }

  /**
   * 待提交分页
   */
  @Override
  public Page<FeeManageItemVo> waitSubmitPage(FeeManageSearchParamPo search) {
    Page<FeeManageItemVo> waitSubmitPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return waitSubmitPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return waitSubmitPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    waitSubmitPage =
      this.baseMapper.waitSubmitPage(
          search.toPage(this.baseMapper.waitSubmitCount(search)),
          search
        );
    List<Long> recordIds = waitSubmitPage
      .getRecords()
      .stream()
      .map(FeeManageItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return waitSubmitPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return waitSubmitPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    waitSubmitPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return waitSubmitPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 费用管理分页查询结果
   */
  @Override
  public Page<?> waitSubmitPageWithChildSearch(FeeManageSearchParamPo search) {
    return appendWithChild(
      waitSubmitPage(search),
      search.toChildSort("itemList")
    );
  }

  /**
   * 查询待提交最后更新时间
   * @param search 查询条件
   * @return 待提交最后更新时间
   */
  @Override
  public Date waitSubmitLastUpdateTime(FeeManageSearchParamPo search) {
    return this.baseMapper.waitSubmitLastUpdateTime(search);
  }

  /**
   * 已处理
   */
  @Override
  public List<FeeManageItemVo> handled(FeeManageSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.handled(search);
  }

  /**
   * 已处理分页
   */
  @Override
  public Page<FeeManageItemVo> handledPage(FeeManageSearchParamPo search) {
    Page<FeeManageItemVo> handledPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return handledPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return handledPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    handledPage =
      this.baseMapper.handledPage(
          search.toPage(this.baseMapper.handledCount(search)),
          search
        );
    List<Long> recordIds = handledPage
      .getRecords()
      .stream()
      .map(FeeManageItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return handledPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return handledPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    handledPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return handledPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 费用管理分页查询结果
   */
  @Override
  public Page<?> handledPageWithChildSearch(FeeManageSearchParamPo search) {
    return appendWithChild(handledPage(search), search.toChildSort("itemList"));
  }

  /**
   * 查询已处理最后更新时间
   * @param search 查询条件
   * @return 已处理最后更新时间
   */
  @Override
  public Date handledLastUpdateTime(FeeManageSearchParamPo search) {
    return this.baseMapper.handledLastUpdateTime(search);
  }

  /**
   * 已作废
   */
  @Override
  public List<FeeManageItemVo> voided(FeeManageSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.voided(search);
  }

  /**
   * 已作废分页
   */
  @Override
  public Page<FeeManageItemVo> voidedPage(FeeManageSearchParamPo search) {
    Page<FeeManageItemVo> voidedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return voidedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return voidedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    voidedPage =
      this.baseMapper.voidedPage(
          search.toPage(this.baseMapper.voidedCount(search)),
          search
        );
    List<Long> recordIds = voidedPage
      .getRecords()
      .stream()
      .map(FeeManageItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return voidedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return voidedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    voidedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return voidedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 费用管理分页查询结果
   */
  @Override
  public Page<?> voidedPageWithChildSearch(FeeManageSearchParamPo search) {
    return appendWithChild(voidedPage(search), search.toChildSort("itemList"));
  }

  /**
   * 查询已作废最后更新时间
   * @param search 查询条件
   * @return 已作废最后更新时间
   */
  @Override
  public Date voidedLastUpdateTime(FeeManageSearchParamPo search) {
    return this.baseMapper.voidedLastUpdateTime(search);
  }
}
